package com.smartcar.tcp;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * TCP客户端管理器
 * 对应原HarmonyOS的TCPClientManager
 */
@Slf4j
@Component
public class TCPClientManager {

    private static TCPClientManager instance;
    private final EventLoopGroup group;
    private Channel channel;
    private final AtomicBoolean isConnected = new AtomicBoolean(false);
    private String serverAddress = "127.0.0.1";
    private int serverPort = 6000;

    private TCPClientManager() {
        this.group = new NioEventLoopGroup();
    }

    public static synchronized TCPClientManager getInstance() {
        if (instance == null) {
            instance = new TCPClientManager();
        }
        return instance;
    }

    /**
     * 初始化网络地址
     */
    public void initNetAddress(String address, int port) {
        this.serverAddress = address;
        this.serverPort = port;
        log.info("TCP客户端初始化网络地址: {}:{}", address, port);
    }

    /**
     * 连接到服务器
     */
    public CompletableFuture<Boolean> connect() {
        CompletableFuture<Boolean> future = new CompletableFuture<>();
        
        if (isConnected.get()) {
            disconnect();
        }

        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new StringDecoder());
                        pipeline.addLast(new StringEncoder());
                        pipeline.addLast(new TCPMessageHandler());
                    }
                });

        bootstrap.connect(new InetSocketAddress(serverAddress, serverPort))
                .addListener((ChannelFutureListener) channelFuture -> {
                    if (channelFuture.isSuccess()) {
                        channel = channelFuture.channel();
                        isConnected.set(true);
                        log.info("TCP连接成功: {}:{}", serverAddress, serverPort);
                        future.complete(true);
                    } else {
                        log.error("TCP连接失败: {}:{}", serverAddress, serverPort);
                        future.complete(false);
                    }
                });

        return future;
    }

    /**
     * 发送消息
     */
    public CompletableFuture<Boolean> sendMessage(String message) {
        CompletableFuture<Boolean> future = new CompletableFuture<>();
        
        if (!isConnected.get() || channel == null) {
            log.warn("TCP未连接，尝试重连");
            connect().thenAccept(success -> {
                if (success) {
                    sendMessageInternal(message, future);
                } else {
                    future.complete(false);
                }
            });
        } else {
            sendMessageInternal(message, future);
        }
        
        return future;
    }

    private void sendMessageInternal(String message, CompletableFuture<Boolean> future) {
        if (channel != null && channel.isActive()) {
            channel.writeAndFlush(message).addListener((ChannelFutureListener) channelFuture -> {
                if (channelFuture.isSuccess()) {
                    log.debug("消息发送成功: {}", message);
                    future.complete(true);
                } else {
                    log.error("消息发送失败: {}", message);
                    future.complete(false);
                }
            });
        } else {
            future.complete(false);
        }
    }

    /**
     * 断开连接
     */
    public void disconnect() {
        if (channel != null) {
            channel.close();
            channel = null;
        }
        isConnected.set(false);
        log.info("TCP连接已断开");
    }

    /**
     * 检查是否连接
     */
    public boolean isConnected() {
        return isConnected.get() && channel != null && channel.isActive();
    }

    /**
     * 关闭资源
     */
    public void shutdown() {
        disconnect();
        if (group != null) {
            group.shutdownGracefully();
        }
    }
} 